package main;

import input.IRCCommand;
import interfaces.CommandHandler;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.apache.log4j.Logger;

import output.IRCOutput;
import output.OutputTypeEnum;
import tools.StringTools;

public class CommandCentral {
   @SuppressWarnings("rawtypes")
   public static void addCommand(final IRCCommand command) {
	  CommandHandler handler = CommandSettings.INSTANCE.getHandlerForCommand(command.get(0));
	  if (handler == null)
		 return;
	  Class[] params = new Class[] { IRCCommand.class, IRCOutput.class };
	  Method method;
	  IRCOutput output = null;
	  try {
		 method = handler.getHandlerMethod("handle" + StringTools.capitalizeFirstLetters(command.get(0)), params);
		 output = new IRCOutput(command.getSource(), command.getSender(), command.getCommand().getPriority());
		 output.setDelivery(command.getCommand().getDelivery()); // start with the default for the command
		 if (method != null) {
			method.invoke(handler, new Object[] { command, output });
			output.setTarget(identifyTarget(output.getDelivery(), command));
		 }
	  } catch (SecurityException e) {
		 Logger.getLogger("Error").error("", e);
	  } catch (IllegalArgumentException e) {
		 Logger.getLogger("Error").error("", e);
	  } catch (IllegalAccessException e) {
		 Logger.getLogger("Error").error("", e);
	  } catch (InvocationTargetException e) {
		 Logger.getLogger("Error").error("", e);
	  }
	  Bot.getInstance().send(output);
   }

   private static String identifyTarget(final OutputTypeEnum type, final IRCCommand command) {
	  switch (type) {
	  case RETURN_TO_SOURCE_NOTICE:
	  case SEND_IN_PM:
	  case NOTICE_USER:
		 return command.getSender();
	  case RETURN_TO_SOURCE_MESSAGE:
		 return command.getSource() == Constants.PM_SOURCE ? command.getSender() : command.getChannel();
	  case SEND_TO_MAIN_CHAN:
	  case NOTICE_MAIN_CHAN:
		 return Main.getBotSettings().getMainChannel();
	  case SEND_TO_ADMIN_CHAN:
	  case NOTICE_ADMIN_CHAN:
		 return Main.getBotSettings().getAdminChannel();
	  }
	  return "";
   }
}
